<template>
  <span v-if="props.showText">{{formData[prop + '_name'] || ''}}</span>
  <el-radio-group
    v-else
    v-model="formData[prop]"
    @change="handleChange"
  >
    <el-radio-button value="" v-if="showAll">全部</el-radio-button>
    <el-radio-button
      v-for="item in options"
      :key="item.key"
      :value="item.key"
    >{{item.value}}</el-radio-button>
  </el-radio-group>
</template>

<script setup>
import { ref, watch, onMounted, onUnmounted, inject } from 'vue';
import { getDictionary } from '@/utils/system';
import emitter from "@/utils/bus";
import tool from "@/utils/tool";

const emit = defineEmits(['change']);
const props = defineProps({
  prop: {
    type: String,
    default: ''
  },
  dictCode: String,
  queryList: Object,
  showText: Boolean,
  showAll: {
    type: Boolean,
    default: () => false
  },
});

const formData = inject('formData');
const loading = ref(true);
const options = ref([]);
const allOptions = ref([]);

const handleChange = () => {
  emit('change');
};

const loadDicAndShow = async(dictCode) => {
  if ((dictCode || '') === '') {
    allOptions.value = [];
    options.value = [];
  } else {
    loading.value = true;
    allOptions.value = await getDictionary(dictCode);
    loading.value = false;
    initCurrValue();
  }
};

const filter = (list, queryList) => {
  if (!list || list.length === 0 || !queryList || queryList.length === 0) return list || [];
  return list.filter(item => queryList.every(query => {
    if (query.filterValue) {
      return item[query.filterFieldId] === query.filterValue;
    } else {
      return item[query.filterFieldId] === formData.value[query.dataFieldName];
    }
  }));
};

const init = () => {
  loadDicAndShow(props.dictCode);
};

const initCurrValue = () => {
  options.value = filter(allOptions.value, props.queryList);
  if (!loading.value && !options.value.find(item => item.key === (formData.value[props.prop] || ''))) {
    formData.value[props.prop] = '';
  }
};

watch(() => tool.deepClone(formData.value), () => {
  initCurrValue();
}, {immediate: true});

watch(() => props.dictCode, () => {
  init();
}, {immediate: true});

onMounted(() => {
  emitter.off("dictionary.change", init);
  emitter.on("dictionary.change", init);
});

onUnmounted(() => {
  emitter.off("dictionary.change", init);
});
</script>